package controller;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import gui.SLogoGUI;
import gui.workspace.Workspace;
import gui.workspace.WorkspaceEditor;
import gui.workspace.WorkspaceTab;
import model.Model;


/**
 * Controller class that handles actions and inputs for workspace of system
 * 
 * @author Troy Ferrell
 * @author David Colon-Smith
 */
public class WorkspaceController extends AbstractController
{
	private static final JFileChooser ourChooser = new JFileChooser(System.getProperties().getProperty("user.dir"));

	public WorkspaceController(Model model) 
	{
		super(model);
	}
	
	// TODO finish implementation
	
	/**
	 * 
	 * 
	 * @param target
	 */
	public void runProgram(Workspace target)
	{
		String program = "";//target.getSelectedText()
		this.myModel.runInput(program);
	}
	
	
	/**
	 * Select All text in current editor
	 * 
	 * @param target
	 */
	public void selectAllText(Workspace target)
	{
		target.getSelectedEditor().selectAll();
	}
	
	/**
	 * Store selected text for pasting
	 * 
	 * @param target
	 */
	public void copyText(Workspace target)
	{
		target.copyText();
	}
	
	/**
	 * Paste saved text at caret of current editor
	 * 
	 * @param target
	 */
	public void pasteText(Workspace target)
	{
		target.pasteText();
	}
	
	/**
	 * Open new logo file
	 * 
	 * @param target
	 */
	public void newLogoFile(Workspace target)
	{
		target.addTab();
	}
	
	/**
	 * Open logo file from memory
	 * @param target
	 */
	public void openLogoFile(Workspace target)
	{
		File openFile = getFileFromDialog(JFileChooser.OPEN_DIALOG);
		try
		{
			Scanner reader = new Scanner(openFile);
			
			StringBuilder sb = new StringBuilder();
			
			while(reader.hasNextLine())
				sb.append(reader.nextLine());
			
			target.addTab(openFile.getName(), sb.toString());
		}catch(IOException e)
		{
			//TODO: handle exception
		}
	}
	
	/**
	 * Save logo file to memory
	 * @param target
	 */
	public void saveLogoFile(Workspace target)
	{
		File myFile = getFileFromDialog(JFileChooser.SAVE_DIALOG);
		WorkspaceEditor editor = target.getSelectedEditor();
		String data = editor.getAllText();
		
		try
		{
		    BufferedWriter out = new BufferedWriter(new FileWriter(myFile));
		    out.write(data);
		    out.close();
	    }catch (Exception e)
	    {
	      // TODO: handle exception
	    }
	}
	
	/**
     * Returns the file chosen by the user.
     */
	private File getFileFromDialog(int dialogType)
	{
		ourChooser.setDialogType(dialogType);
		int response = ourChooser.showDialog(null, null);
		if (response == JFileChooser.APPROVE_OPTION)
		{
			return ourChooser.getSelectedFile();
		}
		
		return null;
	}
	
}
